<script setup lang="ts">
import MeScrollPage from '/src/components/MeScrollPage/MeScrollPage.vue'
import { PageProps } from '@/hooks/usePage'
import { getCacUserAPI, buyCustomerAPI, sendEmailAPI, getUserEmailConfigAPI } from '@/api/cacUser'
import { getCommonConfig } from '@/api/common'
import { getUserCenter } from '@/api/user'
import { getWorldAddress } from '@/api/app'
import { commonConfigKey } from '@/utils/common/enum'
import { callPhone, getRect } from '@/utils/util'
import { useUserStore } from '@/stores/user'
// import { useAppstore } from '@/stores/app'
// const appstore = useAppstore()

const userStore = useUserStore()
import FuiList from '@/components/firstui/fui-list/fui-list.vue'

const tabs = ['公域', '私域', '发送记录']

const itemCoin = ref(0)
const chooseNum = ref(0)

const countryList = ref([])
const getCountry = async () => {
    const { data } = await getWorldAddress({ scene: 'country' })
    countryList.value = data
    // countryName.value = data[0].translations
    // page.params.coutry = countryList.value[0].translations
}

const footerHeight = ref(0)

const tipsHeight = ref(0)

const showTips = ref(false)
onLoad(async (options: any) => {
    const { data } = await getCommonConfig({ keys: commonConfigKey.buyCustomerNeedUCoins })
    itemCoin.value = data[commonConfigKey.buyCustomerNeedUCoins].publicValue
    // console.log(itemCoin.value, '每个用户所需Q币')

    await getCountry()

    const { height } = await getRect('.bottom-box')
    footerHeight.value = height
    console.log('res===========', height)

    const { height: tipsH } = await getRect('.tips')
    console.log('tipsHeight===========', tipsH)
    tipsHeight.value = tipsH

    const res = await getUserEmailConfigAPI({})

    showTips.value = res.data && tabIndex.value > 0

    // language.value = options.lang || appstore.language.value.includes('zh') ? 'zh-cn' : 'en'
})

const meScrollPageRef = ref()

const tabIndex = ref(0)
const page = reactive<PageProps>({
    data: [],
    params: {
        bizTab: 1,
        country: ''
    },
    fetchData: getCacUserAPI // 请求接口 带分页的
})
// tabs 切换
const changeTabs = (e: any) => {
    tabIndex.value = e.index
    page.params.bizTab = e.index + 1

    meScrollPageRef.value?.resetData()
    vals.value = []
    // console.log(tabIndex.value)
}
// 选择客服资源
const vals = ref([])
const change = (val: any) => {
    // console.log(val)
    chooseNum.value = val.detail.value.length
}
// 去支付
const payCoin = async () => {
    if (vals.value.length === 0) {
        uni.showToast({
            title: '请选择客服资源',
            icon: 'none'
        })
        return
    }
    console.log('computeUb=========', computeUb.value)

    // 是否确认支付
    const isConfirm = await uni.showModal({
        title: '确认支付',
        content: computeUb.value
            ? '是否确认支付' + vals.value.length + '线索购买客户资源？'
            : `是否确认支付${itemCoin.value * vals.value.length}U币购买客户资源？`
    })
    if (!isConfirm.confirm) return
    console.log('isConfirm', isConfirm)

    const { code, msg } = await buyCustomerAPI(vals.value)

    console.log('code', code)
    if (code === 0) {
        await userStore.getUser()
        uni.showToast({
            title: '购买成功',
            icon: 'none'
        })
        vals.value = []
        tabIndex.value = 1
    } else {
        uni.showToast({
            title: msg,
            icon: 'none'
        })
    }
}

// 发送邮件
const sendEmail = async (item: any) => {
    if (tabIndex.value === 0) {
        uni.showToast({
            title: '请先购买客户',
            icon: 'none'
        })
        return
    }

    if (!item.email) {
        uni.showToast({
            title: '该用户没有邮箱',
            icon: 'none'
        })
        return
    }

    const r = await uni.showModal({
        title: '提示',
        content: '是否确认发送邮件'
    })
    if (!r.confirm) return
    const res = await sendEmailAPI([item.id])
    if (res.code === 0) {
        uni.showToast({
            title: '邮件发送成功',
            icon: 'none'
        })
        meScrollPageRef.value?.resetData()
    }
}

// 群发邮件
const sendMultiplyEmail = async () => {
    console.log('vals', vals.value)
    const r = await uni.showModal({
        title: '提示',
        content: '是否确认给已选客户发送邮件'
    })
    if (!r.confirm) return

    const res = await sendEmailAPI(vals.value)
    if (res.code === 0) {
        uni.showToast({
            title: '邮件发送成功',
            icon: 'none'
        })
    }
    meScrollPageRef.value?.resetData()
}

// 打电话
const actionPhone = (val: string) => {
    if (tabIndex.value === 0) {
        uni.showToast({
            title: '请先购买客户',
            icon: 'none'
        })
        return
    }
    callPhone(val)
}

// 回退页面
const goback = () => {
    uni.navigateBack()
}

const showCountry = ref(false)

const closePopup = () => {
    showCountry.value = false
}

const countryName = ref({})

const chooseCountry = (data: any) => {
    showCountry.value = false
    page.params.country = data.translations
    countryName.value = data.translations
    meScrollPageRef.value?.resetData()
}

// 计算优先使用线索 再使用u币
const computeUb = computed(() => {
    return vals.value.length <= (userStore.userInfo.memberClueNum || 0)
})


</script>

<template>
    <view
        class="top-box-bg px-[34rpx]"
        :style="{ backgroundImage: `url(${$getImg('/img/cacUser/bg.png')})` }"
    >
        <fui-icon
            :style="{ marginTop: `${$getMenuButtonTop()}px` }"
            name="arrowleft"
            @click="goback"
        ></fui-icon>
        <view class="top-box-title mt-[22rpx]">全球客户</view>

        <view class="u-flex mt-[22rpx]">
            <view
                class="top-box-btn u-flex"
                @click="$jump('/views/subViews/mine/setting/setEmail')"
            >
                <image
                    style="height: 40rpx; width: 40rpx"
                    :src="$getImg('/img/cacUser/xinxiang.png')"
                ></image>
                <view>邮箱</view>
                <image
                    style="height: 12rpx; width: 7rpx"
                    :src="$getImg('/img/cacUser/yousanjiao.png')"
                ></image>
            </view>
            <view class="top-box-btn2 u-flex" @click="showCountry = true">
                <image
                    style="height: 32rpx; width: 32rpx"
                    :src="$getImg('/img/cacUser/dingwei.png')"
                ></image>
                <view>{{ $langFormat(countryName) || '请选择区域' }}</view>
                <image
                    style="height: 12rpx; width: 7rpx"
                    :src="$getImg('/img/cacUser/yousanjiao.png')"
                ></image>
            </view>
        </view>

        <view
            class="top-box-bottom"
            :style="{ backgroundImage: `url(${$getImg('/img/cacUser/juxing.png')})` }"
        >
            <view class="u-flex u-row-between">
                <view class="flex-column gap-[10rpx]">
                    <view class="u-flex">
                        <image
                            style="height: 42rpx; width: 42rpx"
                            :src="$getImg('/img/cacUser/staryuan.png')"
                        ></image>
                        <view class="ml-[14rpx] top-box-bottom-title">我的U币</view>
                        <view class="ml-[16rpx] top-box-bottom-price">{{
                            userStore.userInfo.ucoin || 0
                        }}</view>
                    </view>

                    <view class="u-flex">
                        <image
                            style="height: 42rpx; width: 42rpx"
                            :src="$getImg('/img/cacUser/userLogo.png')"
                        ></image>
                        <view class="ml-[14rpx] top-box-bottom-title">我的线索</view>
                        <view class="ml-[16rpx] top-box-bottom-price">{{
                            userStore.userInfo.memberClueNum || 0
                        }}</view>
                    </view>
                </view>

                <view
                    class="top-box-bottom-btn"
                    @click="$jump('/pages/rechargeCenter/rechargeCenter')"
                    >去充值</view
                >
            </view>
        </view>
    </view>
    <view class="content-box">
        <fui-tabs :tabs="tabs" @change="changeTabs" :current="tabIndex" :center ="true"></fui-tabs>
        <view
            @click="$jump('/views/subViews/mine/setting/setEmail')"
            v-if="showTips"
            class="bg-[#fff7f7] px-[40rpx] py-[10rpx] text-[#F44336] text-[24rpx] flex-between tips"
        >
            <view class="flex gap-[12rpx]">
                <image
                    style="width: 32rpx"
                    mode="widthFix"
                    :src="$getImg('/img/cacUser/xinxiang.png')"
                ></image>
                请先绑定邮箱，发送邮件给客户
            </view>
            <view> 立即绑定 </view>
        </view>
        <MeScrollPage
            type="uni"
            :config="{
                height: $getWindowHeight() - footerHeight - tipsHeight - 298 + 'px'
            }"
            height="800"
            ref="meScrollPageRef"
            :page="page"
        >
            <fui-checkbox-group
                v-if="page.data && page.data.length > 0"
                name="checkbox"
                v-model="vals"
                @change="change"
            >
                <view v-for="item in page.data" :key="item.id" class="item-box">
                    <view class="left">
                        <view class="item">
                            <view class="item-icon" v-if="tabIndex != 2">
                                <fui-checkbox :value="item.id"></fui-checkbox>
                            </view>
                            <view class="item-content">
                                <view class="ellipsis" :class="tabIndex == 2 ? 'max-width-356' : ''">{{ item.name }}</view>
                                <view class="sandNum" v-if="item.sendCount">发送{{ item.sendCount }}次</view>
                            </view>
                        </view>
                        <view class="item">
                            <view class="item-icon">
                                <image class="img" :src="$getImg('/img/cacUser/call.png')"/>
                            </view>
                            <view class="item-content">
                                <view class="ellipsis">{{ item.contactPhone }}</view>
                            </view>
                        </view>
                        <view class="item">
                            <view class="item-icon">
                                <image class="img" :src="$getImg('/img/cacUser/mail.png')"/>
                            </view>
                            <view class="item-content">
                                <view class="ellipsis">{{ item.email }}</view>
                            </view>
                        </view>
                    </view>

                    <view class="right">
                        <view class="country ellipsis">{{ item.country }}</view>

                        <view class="action">
                            <view class="btn" @click="actionPhone(item.contactPhone)">
                                <image class="img" :src="$getImg('/img/cacUser/call-blue.png')"/>
                            </view>

                            <view class="btn" @click="sendEmail(item)">
                                <image class="img" :src="$getImg('/img/cacUser/sms@4x.png')"/>
                            </view>
                        </view>
                    </view>

                </view>
            </fui-checkbox-group>
        </MeScrollPage>
    </view>

    <view class="bottom-box">
        <view class="u-flex u-row-between gap-[10rpx]" v-if="tabIndex === 0">
            <view class="u-flex">
                <view class="bottom-title">已选择{{ chooseNum }}人,</view>
                <view>{{ computeUb ? '需消耗' : '需支付:' }}</view>
                <view class="u-flex gap-[10rpx] ml-[10rpx]">
                    <image
                        style="height: 32rpx; width: 32rpx"
                        :src="
                            computeUb
                                ? $getImg('/img/cacUser/userLogo.png')
                                : $getImg('/img/cacUser/staryuan.png')
                        "
                    ></image>
                    <view class="bottom-price">{{
                        computeUb ? chooseNum : chooseNum * itemCoin
                    }}</view>
                </view>
            </view>
            <view class="bottom-btn" @click="payCoin"> 去支付 </view>
        </view>

        <view v-if="tabIndex === 1" class="u-flex u-row-between">
            <view class="bottom-title">已选择{{ chooseNum }}人</view>
            <view class="u-flex">
                <image
                    style="height: 40rpx; width: 40rpx"
                    :src="$getImg('/img/cacUser/mail-fast.png')"
                ></image>
                <view class="sendEmit-btn ml-[16rpx]" @click="sendMultiplyEmail">群发邮件</view>
            </view>
        </view>
        <fui-safe-area></fui-safe-area>
    </view>

    <fui-bottom-popup :show="showCountry" @close="closePopup">
        <view>
            <view class="fui-scroll__wrap">
                <view class="fui-title">国家</view>
            </view>
            <scroll-view scroll-y class="fui-scroll__view" style="height: 60vh">
                <fui-list>
                    <fui-list-cell
                        v-for="(item, index) in countryList"
                        :key="index"
                        @click="chooseCountry(item)"
                        >{{ $langFormat(item.translations) }}</fui-list-cell
                    >
                </fui-list>
            </scroll-view>
        </view>
    </fui-bottom-popup>
</template>

<style scoped lang="scss">
.fui-title {
    font-size: 30rpx;
    font-weight: bold;
    text-align: center;
    padding-bottom: 24rpx;
}

.fui-scroll__wrap {
    padding-top: 30rpx;
    position: relative;
}
.top-box-bg {
    height: 501rpx;
    background-size: 100% 100%;
    display: flex;
    flex-direction: column;
    position: relative;

    .top-box-title {
        font-weight: 600;
        font-size: 38rpx;
        color: #3d3d3d;
    }



    .top-box-btn {
        background: #fbfcfe;
        padding: 14rpx 14rpx 12rpx 12rpx;
        border-radius: 5px;
        font-size: 28rpx;
        color: #3d3d3d;
        gap: 10rpx;
    }

    .top-box-btn2 {
        margin-left: 20rpx;
        background: #fbfcfe;
        padding: 14rpx 28rpx 12rpx 18rpx;
        border-radius: 5px;
        font-size: 28rpx;
        color: #3d3d3d;
        gap: 10rpx;
    }

    .top-box-bottom {
        //box-sizing: border-box;
        width: calc(100% - 80rpx);
        height: 116rpx;
        padding: 12rpx 40rpx 0 32rpx;
        background-size: 100% 100%;
        background-repeat: no-repeat;
        background-position: center center;
        position: absolute;
        bottom: 10rpx;
        left: 0;
        right: 0;
        margin: auto 40rpx;
    }

    .top-box-bottom-title {
        font-size: 28rpx;
        color: #3d3d3d;
    }

    .top-box-bottom-price {
        font-weight: 600;
        font-size: 30rpx;
        color: #3d3d3d;
    }

    .top-box-bottom-btn {
        padding: 12rpx 24rpx;
        color: #f58b25;
        font-size: 24rpx;
        box-shadow: 0px 0px 3px 0px #f6aa61;
        border-radius: 287px;
        background: #ffffff;
    }
}

.content-box {
    z-index: 2;
    overflow: hidden;
    border-radius: 50rpx 50rpx 0 0;
    margin-top: -10rpx;


    .item-box {
        padding: 40rpx;
        border-bottom: 1rpx solid #efefef;

        display: flex;
        justify-content: space-between;
        width: 100%;

        .left {

            .item {
                display: flex;

                &:nth-child(1), &:nth-child(2) {
                    margin-bottom: 30rpx;
                }

                .item-icon {
                    margin-right: 20rpx;

                    .img {
                        width: 36rpx;
                        height: 36rpx;
                    }
                }

                .item-content {
                    display: flex;
                    width: 100%;

                    & > view:first-child {
                        //flex: 8;
                        max-width: 300rpx;
                        font-size: 30rpx;
                        color: #303030;
                    }

                    .max-width-356 {
                        max-width: 356rpx;
                    }


                    .sandNum {
                        //flex: 2;
                        margin-left: 26rpx;
                        padding: 4rpx 14rpx;
                        font-size: 22rpx;
                        color: #8f8f8f;
                        border-radius: 248px;
                        background: #F5F5F5;
                        text-align: center;
                    }
                }
            }
        }

        .right {
            width: 170rpx;

            .country {
                text-align: right;
                margin-bottom: 46rpx;
            }
            .action {
                display: flex;
                justify-content: flex-start;
                align-items: center;

                .btn {
                    width: 68rpx;
                    height: 68rpx;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    border-radius: 112.67px;
                    background: #e6edff;

                    &:first-child {
                        margin-right: 24rpx;
                    }

                    .img {
                        width: 34rpx;
                        height: 34rpx;
                    }
                }
            }
        }
    }

}

.bottom-box {
    padding: 0 36rpx;
    position: sticky;
    bottom: 0;
    width: 100%;
    background: #ffffff;
    z-index: 99;
    display: flex;
    align-items: center;
    & > view {
        width: 100%;
        height: 90rpx;
    }

    .bottom-btn {
        background: linear-gradient(112deg, #376af7 14%, #40a9ff 83%);
        padding: 14rpx 40rpx;
        border-radius: 618px;
        color: #ffffff;
        font-size: 28rpx;
    }
    .bottom-title {
        color: #999999;
    }
    .bottom-price {
        color: #376af7;
        font-weight: 600;
    }
    .sendEmit-btn {
        padding: 14rpx 38rpx;
        border-radius: 618px;
        background: linear-gradient(105deg, #376af7 14%, #40a9ff 83%);
        color: #ffffff;
        font-size: 28rpx;
    }
}
</style>
